Grokking Meta Coding Interview
Rate this course
Ask Author
Contribute
Back to course home

0% completed

Vote For New Content
Introduction
Who Should Take This Course?
Meta Easy Problems
Toeplitz Matrix (easy)
Solution: Toeplitz Matrix
Remove All Adjacent Duplicates In String (easy)
Solution: Remove All Adjacent Duplicates In String
Minimum Depth of a Binary Tree (easy)
Solution: Minimum Depth of a Binary Tree
Tree Diameter (easy)
Solution: Tree Diameter
Island Perimeter (easy)
Solution: Island Perimeter
Moving Average from Data Stream (easy)
Solution: Moving Average from Data Stream
Move Zeroes (easy)
Solution: Move Zeroes
Missing Ranges (easy)
Solution: Missing Ranges
Palindrome Permutation (easy)
Solution: Palindrome Permutation
Rank Transform of an Array (easy)
Solution: Rank Transform of an Array
Meta Medium Problems
Diagonal Traverse (medium)
Solution: Diagonal Traverse
Shortest Path in Binary Matrix (medium)
Solution: Shortest Path in Binary Matrix
Maximum Swap (medium)
Solution: Maximum Swap
Custom Sort String (medium)
Solution: Custom Sort String
Binary Tree Vertical Order Traversal (medium)
Solution: Binary Tree Vertical Order Traversal
Buildings With an Ocean View (medium)
Solution: Buildings With an Ocean View
Basic Calculator II (medium)
Solution: Basic Calculator II
Nested List Weight Sum (medium)
Solution: Nested List Weight Sum
Dot Product of Two Sparse Vectors (medium)
Solution: Dot Product of Two Sparse Vectors
Max Consecutive Ones III (medium)
Solution: Max Consecutive Ones III
Subarray Sum Equals K (medium)
Solution: Subarray Sum Equals K
Next Permutation (medium)
Solution: Next Permutation
Simplify Path (medium)
Solution: Simplify Path
Lowest Common Ancestor of a Binary Search Tree (medium)
Solution: Lowest Common Ancestor of a Binary Search Tree
'K' Closest Points to the Origin (medium)
Solution: 'K' Closest Points to the Origin
Sum of Path Numbers (medium)
Solution: Sum of Path Numbers
Merge Intervals (medium)
Solution: Merge Intervals
Right View of a Binary Tree (medium)
Solution: Right View of a Binary Tree
Number of Islands (medium)
Solution: Number of Islands
Clone Graph (medium)
Solution: Clone Graph
Missing Element in Sorted Array (medium)
Solution: Missing Element in Sorted Array
Number of Substrings Containing All Three Characters (medium)
Solution: Number of Substrings Containing All Three Characters
Capacity To Ship Packages Within D Days (medium)
Solution: Capacity To Ship Packages Within D Days
Count and Say (medium)
Solution: Count and Say
Contiguous Array (medium)
Solution: Contiguous Array
Meta Hard Problems
Sliding Window Median (hard)
Solution: Sliding Window Median
Alien Dictionary (hard)
Solution: Alien Dictionary
Minimum Window Substring (hard)
Solution: Minimum Window Substring
Best Meeting Point (hard)
Solution: Best Meeting Point
Maximum Sum of 3 Non-Overlapping Subarrays (hard)
Solution: Maximum Sum of 3 Non-Overlapping Subarrays
Making A Large Island (hard)
Solution: Making A Large Island
Basic Calculator (Hard)
Solution: Basic Calculator
Serialize and Deserialize Binary Tree (hard)
Solution: Serialize and Deserialize Binary Tree
Longest Increasing Path in a Matrix (hard)
Solution: Longest Increasing Path in a Matrix
Valid Palindrome III (hard)
Solution: Valid Palindrome III
Solution: Longest Increasing Path in a Matrix

Problem Statement

Given a 2D matrix of size m x n, return the length of the longest increasing path in the matrix. The increasing path should have each element should be greater than the previous element in the path.

It is given that you can move only in 4-directions: left, right, top, and bottom.

Examples

Example 1:

  • Input: matrix =
[[3, 4, 5], 
 [3, 2, 6], 
 [2, 2, 1]]
  • Expected Output: 4
Image
  • Justification: The longest increasing path is 3 -> 4 -> 5 -> 6. No other path has a greater length.

Example 2:

  • Input: matrix =
[[5,4,9],
 [5,3,8],
 [4,6,7]]
  • Expected Output: 5
Image
  • Justification: The longest increasing path starts from the cell with value 3 (1, 1), moving to 6, then 7, 8, and finally 9.

Example 3:

  • Input: matrix =
[[1, 2, 3, 4], 
 [6, 5, 4, 3], 
 [7, 8, 9, 2], 
 [10, 11, 12, 1]]
  • Expected Output: 10
Image
  • Justification: The longest increasing path is 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 11 -> 12.

Solution

To solve this problem, we'll use dynamic programming with depth-first search (DFS). The idea is to store the length of the longest increasing path starting from each cell, so we do not need to recompute it each time. This approach works because the longest path from any given cell is fixed once calculated.

In the beginning, we'll create a cache matrix of the same size as the input matrix to store the lengths of the longest paths. Then, we'll perform a DFS from each cell, checking its four adjacent cells (up, down, left, right). If an adjacent cell has a higher value, we'll continue the DFS from that cell. We'll update the cache with the maximum length found during these searches. This approach is efficient because it combines the exhaustive nature of DFS with the optimization of dynamic programming, allowing us to avoid unnecessary recalculations.

Step-by-step Algorithm

  1. Initialize Cache: Create a cache matrix of the same size as the input matrix. Initialize all values to 0. This cache will store the length of the longest increasing path starting from each cell.

  2. Iterate Through Matrix: Go through each cell in the input matrix. For each cell, perform a Depth-First Search (DFS) if its corresponding value in the cache is 0.

  3. Depth-First Search (DFS):

    • If the current cell is out of bounds or its value is not greater than the previous cell's value, return 0.
    • If the cache value at the current cell is non-zero, return it (to avoid recomputation).
    • Explore all four adjacent cells (up, down, left, right). If an adjacent cell has a greater value, recursively call DFS on that cell.
    • Update the cache value for the current cell as 1 plus the maximum length obtained from the adjacent cells.
    • Return the cache value for the current cell.
  4. Track Maximum Path Length: During the iteration, keep track of the maximum length found across all cells.

  5. Return Result: After completing the iterations, return the maximum path length found.

Algorithm Walkthrough

Let's use the matrix:

[[5, 4, 9],
 [5, 3, 8],
 [4, 6, 7]]

Step 1: Start DFS at (0, 0) - Value 5

  • Initial exploration. There are not any adjacent values greater than 5.
  • Cache matrix after update:
    1 0 0 
    0 0 0 
    0 0 0 
    
  • maxPath: 1

Step 2: Explore (0, 1) - Value 4

  • Finds a path to 5, updates its path length to 2.
  • Cache matrix:
    1 2 0 
    0 0 0 
    0 0 0 
    
  • maxPath: 2

Step 3: Move to (0, 2) - Value 9

  • Directly reaches the end of a potential path.
  • Cache matrix update reflects this cell as an endpoint of a path.
    1 2 1 
    0 0 0 
    0 0 0 
    
  • maxPath: 2

Step 4: Explore (1, 0) - Value 5

  • Same value as (0,0), no increase.
  • Cache matrix:
    1 2 1 
    1 0 0 
    0 0 0 
    
  • maxPath: 2

Step 5: Explore from (1, 1) - Value 3

  • Moving to the top: Find a path from 3 to 4, update maxLength to 1 + 2 = 3.

  • Moving to the bottom: Find a path from 3 to 6.

  • Next, explore the path from 6 to 7, as it is the only valid move.

  • Next, explore the path from 7 to 8, as it is the only valid move.

  • Next, explore the path from 8 to 9, as it is the only valid move.

  • After exploring, the 8 to 9 path, the updated cache matrix is:

    1 2 1
    1 0 2 
    0 0 0 
    
  • After exploring, the 7 to 8 path, the updated cache matrix is:

    1 2 1
    1 0 2 
    0 0 3 
    
  • After exploring, the 6 to 7 path, the updated cache matrix is:

    1 2 1
    1 0 2 
    0 4 3 
    
  • After exploring, the 3 to 6 path, the updated cache matrix is:

    1 2 1
    1 5 2 
    0 4 3 
    
  • maxPath: 5.

  • Continue traversing each cell of the matrix this way. The length of the maximum increasing path would be 5 and path would be either 3 -> 6 -> 7 -> 8 -> 9 or 4 -> 6 -> 7 -> 8 -> 9

Code

Java
Saved to Cloud

. . . .

Complexity Analysis

  • Time Complexity: O(M * N), where M and N are the dimensions of the matrix. This is because each cell in the matrix is the starting point for DFS only once, thanks to caching.

  • Space Complexity: O(M * N), due to the cache matrix and recursion stack. The cache stores the longest path starting from each cell, and the recursion stack depth can potentially be as large as the number of cells in the matrix in the worst case.

Longest Increasing Path in a Matrix (hard)
Valid Palindrome III (hard)
Mark as Completed

On this page

Problem Statement

Examples

Solution

Step-by-step Algorithm

Algorithm Walkthrough

Code

Complexity Analysis